package com.itheima.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;


/**
 * @Author: taku
 * @CreateTime: 2020-04-26 17:13
 * @Description: 消息消费者
 */
public class Consumer {
    public static void main(String[] args) {
        try {
            // 创建工厂
            ConnectionFactory factory = new ConnectionFactory();
            // 设置端口,ip,用户,密码
            factory.setUsername("admin");
            factory.setPassword("admin");
            factory.setVirtualHost("itheima");
            factory.setPort(5672);
            factory.setHost("localhost");
            // 重建connect
            Connection connection = factory.newConnection();
            // 重建chanel
            Channel channel = connection.createChannel();
            // 声明队列
            channel.queueDeclare("simple_queue",true,false,false,null);
            com.rabbitmq.client.Consumer consumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope,
                                           AMQP.BasicProperties properties,
                                           byte[] body)
            /**
             * @param consumerTag 消费者标签，在channel.basicConsume时候可以指定
             * @param envelope 信封，消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志(收到消息失败后是否需要重新发送)
             * @param properties  属性信息(生产者的发送时指定)
             * @param body 消息内容
             */
            throws IOException
                {
                    String exchange = envelope.getExchange();
                    String routingKey = envelope.getRoutingKey();
                    System.out.println(new String(body) + "   routingKey:" + routingKey+
                            "   exchanger: " + exchange);
                }
            };
            channel.basicConsume("simple_queue",true,consumer);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
